package com.itgone.config;

import com.itgone.annotation.IgnoreResultAdvice;
import com.itgone.common.R;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.Objects;


@RestControllerAdvice
public class ResponseResultHandler implements ResponseBodyAdvice<Object> {
    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        // 判断当前类是否有@IgnoreResultAdvice注解
        Class<?> containingClass = returnType.getContainingClass();
        IgnoreResultAdvice annotation = containingClass.getAnnotation(IgnoreResultAdvice.class);
        if (Objects.nonNull(annotation)) {
            return false;
        }
        // 判断当前方法是否有@IgnoreResultAdvice注解
        IgnoreResultAdvice methodAnnotation = returnType.getMethodAnnotation(IgnoreResultAdvice.class);
        return !Objects.nonNull(methodAnnotation);
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        if (body instanceof R) {
            return body;
        }
        return R.ok(body);
    }
}
